﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Green.FastInvoker;
using Green.Utility;

namespace Green.AgileMapper
{
    public class ExpressionMappingRule : IMappingRule, IXmlConfigLoad
    {
        public string FromPoperty
        { get; set; }

        public string Expression
        { get; private set; }

        public ExpressionMappingRule(string fromPoperty, string expression)
        {
            this.FromPoperty = fromPoperty;
            this.Expression = expression;
        }

        public ExpressionMappingRule()
        {
        }


        #region IMappingRule 成员

        /// <summary>
        /// 根据 To得到From
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpFrom(object from, object to)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("domainObj", to);
            var value = DynamicExpression.Compute(dict, PropertyAccessor.GetPropertyType(from, this.FromPoperty), this.Expression);
            // value = value.ChangeType(PropertyAccessor.GetPropertyType(from, this.FromPoperty));
            PropertyAccessor.Set(from, this.FromPoperty, value);
        }
        /// <summary>
        /// 根据From得到To
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpTo(object from, object to)
        {

        }

        #endregion

        #region IXmlConfigLoad 成员

        public void LoadXmlConfig(Dictionary<string, object> propertys)
        {
            this.FromPoperty = propertys.TryGetValue<string, string>("FromPoperty", string.Empty);
            this.Expression = propertys.TryGetValue<string, string>("Expression", string.Empty);
        }

        #endregion
    }
}
